import {v4} from "uuid"
import { RequestHandler } from "express";
import { DataStore } from "../../data";
import { UserInfo } from "os";
import { User } from "../../data/types";
import { randomUUID } from "crypto";
import { getFileUploader } from "../../general/static";
import { APIError, publicInfor } from "../../model/shared/APIErroy";

export const apiPostUserInfor: RequestHandler = (req, res, next) => {
    console.log(req.body);
    let newUser = {
        id:v4(),
        userId: req.body.userId | 1,
        title: req.body.title,
        body: req.body.body,
        price: req.body.price,
        currency: req.body.currency,
        imgs:[]

    } as User
    let requireFields = ["title", "body"];
    let givecFieds=Object.getOwnPropertyNames(req.body);
    if(!requireFields.every(item=>givecFieds.includes(item))){
         next(new APIError("data missing","not all properties given",400));
         return
    }
    DataStore.user.push(newUser  );
    // res.send("data add success")
    res.json(new publicInfor("data add success",200,newUser));
}
export const apiUploadImage: RequestHandler = (req, res, next) => {
    let index = DataStore.user.findIndex(item => req.params.id == item.id)
    if (index == -1) {
        next(new APIError("Data missing","id not found",400));
    }
    else {
        let uploader=getFileUploader(req.app.get("env"))
        uploader(req,res,error=>{
            if(error){
                console.log("error:"+error)
                next(new APIError("error","upload image fail",500))
            }
            else{
                DataStore.user[index].imgs.push(req.file.filename)
                res.json(new publicInfor("user added",200))
            }
        })
    }
}